//
//  BSKCancelAlarmClockViewController.m
//  AlarmClock
//
//  Created by aaaa on 2016/10/12.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "BSKCancelAlarmClockViewController.h"
#import "SDAutoLayout.h"
#import <AVFoundation/AVFoundation.h>
#import "BSKConsts.h"
#import "UIViewController+BSKToast.h"
#import "BSKSington.h"
@interface BSKCancelAlarmClockViewController ()<AVAudioPlayerDelegate>
@property (nonatomic,strong) UILabel * timeLabel;
@property (nonatomic,strong) UILabel * bgView;
@property (nonatomic,strong) UIImageView * bgImageView;
@property (nonatomic,strong) UIView * progressView;
@property (nonatomic,strong) UILabel * progressLabel;
@property (nonatomic,strong) UILabel * panLabel;
@property (nonatomic,strong) AVAudioPlayer * player;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UIButton * oneMoreTimeButton;
@property (nonatomic,strong) UILabel *questionLabel;
@property (nonatomic,strong) UILabel *answerLabel;
@property (nonatomic,assign) NSInteger firstRandom;
@property (nonatomic,assign) NSInteger sencondRandom;
@property (nonatomic,strong) NSString *answerString;
@property (nonatomic,assign) BOOL isRight;
@property (nonatomic,strong) UIView *backView;
@end

@implementation BSKCancelAlarmClockViewController

- (instancetype)initWithMode:(BSKCancelAlarmClockVCMode) mode
{
    self = [super init];
    if (self) {
        self.Mode = mode;
        _playSound = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.0477 green:0.0464 blue:0.0846 alpha:1.0];
    self.bgImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yk.jpeg"]];
    self.bgImageView.alpha = 0.5;
    [self.view addSubview:self.bgImageView];
    self.bgImageView.sd_layout
    .leftSpaceToView(self.view,0)
    .topSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,0);
    self.timeLabel = [[UILabel alloc]init];
    self.timeLabel.font = [UIFont systemFontOfSize:50];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    NSDate * date = [NSDate date];
    NSDateFormatter * formater = [[NSDateFormatter alloc]init];
    [formater setDateFormat:@"HH:mm"];
    self.timeLabel.text =[formater stringFromDate:date];
    [self.view addSubview:self.timeLabel];
    self.timeLabel.sd_layout
    .topSpaceToView(self.view,ScreenWidth / 6)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .heightIs(50);
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.dic[@"label"];
    [self.view addSubview:self.titleLabel];
    self.titleLabel.sd_layout
    .topSpaceToView(self.timeLabel,0)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .heightIs(30);
    
    // 随机产生两个4位随机数
    self.firstRandom = [self getRandomNumber];
    self.sencondRandom = [self getRandomNumber];
    self.questionLabel = [[UILabel alloc]init];
    self.questionLabel.font = [UIFont systemFontOfSize:25];
    self.questionLabel.textColor = [UIColor whiteColor];
    self.questionLabel.textAlignment = NSTextAlignmentCenter;
    self.questionLabel.text = [NSString stringWithFormat:@"%ld + %ld = ?",self.firstRandom,self.sencondRandom];
    [self.view addSubview:self.questionLabel];
    self.questionLabel.sd_layout
    .topSpaceToView(self.titleLabel,10)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .heightIs(30);
    
    
    self.answerLabel = [[UILabel alloc]init];
    self.answerLabel.font = [UIFont systemFontOfSize:25];
    self.answerLabel.textColor = [UIColor whiteColor];
    self.answerLabel.textAlignment = NSTextAlignmentCenter;
    self.answerLabel.text = @"请输入正确答案";
    self.answerLabel.hidden = NO;
    [self.view addSubview:self.answerLabel];
    self.answerLabel.sd_layout
    .topSpaceToView(self.questionLabel,10)
    .leftSpaceToView(self.view,(ScreenWidth - ScreenWidth / 1.5) / 2)
    .widthIs(ScreenWidth / 1.5)
    .heightIs(30);
    [self.answerLabel updateLayout];
    
    self.backView = [[UIView alloc]init];
    self.backView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.backView];
    self.backView.hidden = NO;
    self.backView.sd_layout
    .topSpaceToView(self.answerLabel,0)
    .leftSpaceToView(self.view,0)
    .rightSpaceToView(self.view,0)
    .bottomSpaceToView(self.view,100);
    
    for (int i = 0 ;i < 11; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(ScreenWidth *0.1+ i % 3 * (ScreenWidth-ScreenWidth*0.2)/3, i / 3 * (ScreenWidth-ScreenWidth*0.2)/5, (ScreenWidth-ScreenWidth*0.2)/3, (ScreenWidth-ScreenWidth*0.2)/5);
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:25];
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        if (i < 9) {
            [button setTitle:[NSString stringWithFormat:@"%d",i+1] forState:UIControlStateNormal];
        } else {
            if (i == 9) {
                [button setTitle:@"清除" forState:UIControlStateNormal];
            }
            if (i == 10) {
                [button setTitle:@"0" forState:UIControlStateNormal];
            }
        }
        button.tag = i + 250;
        [self.backView addSubview:button];
    }
    
    self.bgView = [[UILabel alloc]init];
    self.bgView.font = [UIFont systemFontOfSize:20];
    self.bgView.textColor = [UIColor colorWithRed:0.7679 green:0.7679 blue:0.7679 alpha:1.0];
    self.bgView.textAlignment = NSTextAlignmentCenter;
    self.bgView.text =@"滑动关闭 〉〉";
    self.bgView.layer.cornerRadius = ScreenWidth / 5 / 2;
    self.bgView.layer.masksToBounds = YES;
    self.bgView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.25];
    [self.view addSubview:self.bgView];
    self.bgView.sd_layout
    .bottomSpaceToView(self.view,ScreenWidth / 10)
    .leftSpaceToView(self.view,10)
    .rightSpaceToView(self.view,10)
    .heightIs(ScreenWidth / 5);
    [self.bgView updateLayout];
    
    self.progressView = [[UIView alloc]init];
    self.progressView.backgroundColor = [UIColor colorWithRed:0.1142 green:0.6238 blue:0.9059 alpha:1.0];
    self.progressView.layer.cornerRadius = ScreenWidth / 5 / 2;
    [self.bgView addSubview:self.progressView];
    self.progressView.sd_layout
    .topSpaceToView(self.bgView,0)
    .leftSpaceToView(self.bgView,0)
    .rightSpaceToView(self.bgView,self.bgView.bounds.size.width-(ScreenWidth / 5))
    .heightIs(ScreenWidth / 5);
    
    self.progressLabel = [[UILabel alloc]init];
    self.progressLabel.backgroundColor = [UIColor colorWithRed:0.1142 green:0.6238 blue:0.9059 alpha:1.0];
    self.progressLabel.font = [UIFont systemFontOfSize:20];
    self.progressLabel.textColor = [UIColor whiteColor];
    self.progressLabel.textAlignment = NSTextAlignmentCenter;
    self.progressLabel.text = @"继续滑动";
    self.progressLabel.layer.cornerRadius = ScreenWidth / 5 / 2;
    self.progressLabel.layer.masksToBounds = YES;
    [self.progressView addSubview:self.progressLabel];
    self.progressLabel.sd_layout
    .topSpaceToView(self.progressView,0)
    .leftSpaceToView(self.progressView,0)
    .rightSpaceToView(self.progressView,0)
    .heightIs(ScreenWidth / 5);
    
    
    self.panLabel = [[UILabel alloc]init];
    self.panLabel.font = [UIFont systemFontOfSize:20];
    self.panLabel.textColor = [UIColor whiteColor];
    self.panLabel.textAlignment = NSTextAlignmentCenter;
    self.panLabel.text =@"关闭";
    self.panLabel.layer.cornerRadius = ScreenWidth / 5 / 2;
    self.panLabel.layer.masksToBounds = YES;
    self.panLabel.backgroundColor = [UIColor colorWithRed:0.9703 green:0.2575 blue:0.3015 alpha:1.0];
    [self.bgView addSubview:self.panLabel];
    self.panLabel.sd_layout
    .topSpaceToView(self.bgView,0)
    .leftSpaceToView(self.bgView,0)
    .widthIs(ScreenWidth / 5)
    .heightIs(ScreenWidth / 5);
    
    self.bgView.userInteractionEnabled = YES;
    self.panLabel.userInteractionEnabled = YES;
    UIPanGestureRecognizer * pangesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    [self.panLabel addGestureRecognizer:pangesture];
    
    self.oneMoreTimeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.oneMoreTimeButton setTitle:[NSString stringWithFormat:@"再睡%ld分钟",self.moreMinutes] forState:UIControlStateNormal];
    self.oneMoreTimeButton.layer.cornerRadius = 25;
    self.oneMoreTimeButton.layer.borderColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0].CGColor;
    self.oneMoreTimeButton.alpha = 0.5;
    self.oneMoreTimeButton.layer.borderWidth = 1;
    [self.oneMoreTimeButton addTarget:self action:@selector(oneMoreTimeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.oneMoreTimeButton];
    self.oneMoreTimeButton.sd_layout
    .widthIs(200)
    .heightIs(50)
    .centerXEqualToView(self.view)
    .bottomSpaceToView(self.bgView,10);
    
    
    if (_Mode == BSKCancelAlarmClockVCStopWatchMode) {
        self.questionLabel.hidden = YES;
        self.answerLabel.hidden = YES;
        self.backView.hidden = YES;
        self.oneMoreTimeButton.hidden = YES;
        self.titleLabel.hidden = YES;
    }
    
    if (_Mode == BSKCancelAlarmClockVCAlarmClockHardMode) {
        self.titleLabel.hidden = NO;
        self.questionLabel.hidden = NO;
        self.oneMoreTimeButton.hidden = NO;
        
        NSInteger countNumber = -1;
        NSNumber * count = self.dic[@"againCount"];
        if (count) {
            countNumber = [count integerValue];
        }
        if (countNumber==0) {
            self.oneMoreTimeButton.hidden = YES;
        }else{
            self.oneMoreTimeButton.hidden = NO;
        }
    }
    if (_Mode == BSKCancelAlarmClockVCAlarmClockNormalMode) {
        
    }
    // Do any additional setup after loading the view.
}

//获取一个4位随机整数

-(NSInteger)getRandomNumber
{
    NSInteger x = arc4random() % 9 + 1;
    NSInteger y = arc4random() % 100;
    return x * 100 + y;
}

-(void)viewWillAppear:(BOOL)animated{
    
    
    NSString * bell = self.dic[@"bell"];
    if (!bell) {
        bell = @"fallbackring";
    }

    
    NSString * filePath = [[NSBundle mainBundle] pathForResource:bell ofType:@"wav"];
    NSURL * fileURL = [NSURL fileURLWithPath:filePath];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL fileTypeHint:@"wav" error:NULL];
    self.player.delegate = self;
    [self.player prepareToPlay];
    [self.player play];
}

-(void)viewDidAppear:(BOOL)animated{
    if (self.Mode!=BSKCancelAlarmClockVCStopWatchMode) {
        [self startAnswer];
        [self MakeToast:@"开始答题！！答题时间20秒" WithTime:2];
    }
}
#pragma mark - action
- (void)startAnswer{
    // 产生随机问题
    self.firstRandom = [self getRandomNumber];
    self.sencondRandom = [self getRandomNumber];
    self.questionLabel.text = [NSString stringWithFormat:@"%ld + %ld = ?",self.firstRandom,self.sencondRandom];
    [self performSelector:@selector(timerPressed) withObject:nil afterDelay:20];
}

- (void)buttonPressed:(UIButton *)sender {
    NSInteger tag = sender.tag - 250 +1;
    if (tag == 11) {
        tag = 0;
    }
    if (tag < 11) {
        if ([self.answerLabel.text isEqualToString:@"请输入正确答案"]) {
            self.answerString = [NSString stringWithFormat:@"%ld",tag];
        } else {
            self.answerString = [NSString stringWithFormat:@"%@%ld",self.answerString,tag];
        }
        self.answerLabel.text = self.answerString;
    }
    if (tag == 10) {
        self.answerLabel.text = @"请输入正确答案";
    }
}

- (void)timerPressed {
    [self MakeToast:@"答题时间到,重新开始20秒计时" WithTime:3];
    self.answerLabel.text = @"请输入正确答案";
    [self startAnswer];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [player play];
}
-(void)viewDidDisappear:(BOOL)animated{
    [self.player stop];
}


-(void)oneMoreTimeButtonAction:(UIButton *)sender{
    if (self.delegate) {
        if ([self.delegate respondsToSelector:@selector(CancelAlarmClockVC:moreMinutesAction:)]) {
            [self.delegate CancelAlarmClockVC:self moreMinutesAction:self.moreMinutes];
        }
    }
//    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)panAction:(UIPanGestureRecognizer *)gesture{
    CGPoint p = [gesture translationInView:self.bgView];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        {
            
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            if (p.x<0) {
                p.x=0;
            }
            if (p.x<self.bgView.bounds.size.width-ScreenWidth/5) {
                self.panLabel.sd_layout
                .leftSpaceToView(self.bgView,p.x);
                self.progressLabel.text = @"继续滑动";
                [self.panLabel updateLayout];
                self.progressView.sd_layout
                .rightSpaceToView(self.bgView,self.bgView.bounds.size.width-ScreenWidth / 5-p.x);
                [self.progressView updateLayout];
            }else{
                self.panLabel.sd_layout
                .leftSpaceToView(self.bgView,self.bgView.bounds.size.width-ScreenWidth/5);
                [self.panLabel updateLayout];
                self.progressLabel.text = @"松开即可关闭";
                self.progressView.sd_layout
                .rightSpaceToView(self.bgView,0);
                [self.progressView updateLayout];
            }
            
        }
            break;
        case UIGestureRecognizerStateEnded:{
            if (self.progressView.bounds.size.width == self.bgView.bounds.size.width) {
                NSLog(@"关闭");
                
                NSInteger answer = self.firstRandom + self.sencondRandom;
                
                BOOL close =[self.answerLabel.text integerValue] == answer;
                if (self.Mode==BSKCancelAlarmClockVCStopWatchMode) {
                    close = YES;
                }
                if (close) {
                    if (self.delegate) {
                        if ([self.delegate respondsToSelector:@selector(CancelAlarmClockVC:didClosed:)]) {
                            [self.delegate CancelAlarmClockVC:self didClosed:YES];
                        }
                    }
//                    [self dismissViewControllerAnimated:YES completion:nil];
                    
                    [[BSKSington sharBSKSington].rootViewController popViewControllerAnimated:YES];
                    
                } else {
                    [self MakeToast:@"问题回答错误" WithTime:2];
                    [UIView animateWithDuration:0.25 animations:^{
                        self.panLabel.sd_layout
                        .leftSpaceToView(self.bgView,0);
                        [self.panLabel updateLayout];
                        self.progressView.sd_layout
                        .rightSpaceToView(self.bgView,self.bgView.bounds.size.width-ScreenWidth / 5);
                        [self.progressView updateLayout];
                    } completion:^(BOOL finished) {
                        self.progressLabel.text = @"继续滑动";
                    }];
                    
                }
                
                break;
            }
            
        }
        default:{
            self.progressLabel.text = @"";
            [UIView animateWithDuration:0.25 animations:^{
                self.panLabel.sd_layout
                .leftSpaceToView(self.bgView,0);
                [self.panLabel updateLayout];
                self.progressView.sd_layout
                .rightSpaceToView(self.bgView,self.bgView.bounds.size.width-ScreenWidth / 5);
                [self.progressView updateLayout];
            } completion:^(BOOL finished) {
                self.progressLabel.text = @"继续滑动";
            }];
            
        }
            break;
    }
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

@end
